package com.mingren.manager.websocket;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.mingren.manager.auth.SpaceUserAuthManager;
import com.mingren.manager.auth.model.SpaceUserPermissionConstant;
import com.mingren.model.domain.Picture;
import com.mingren.model.domain.Space;
import com.mingren.model.domain.User;
import com.mingren.model.enums.SpaceTypeEnum;
import com.mingren.service.PictureService;
import com.mingren.service.SpaceService;
import com.mingren.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author 曹宏福
 * @version 1.0
 * WebSocket拦截器:验证权限 如用户没有在团队空间内编辑图片的权限则拒绝握手
 */
@Component
@Slf4j
public class WsHandshakeInterceptor implements HandshakeInterceptor {

    @Resource
    private UserService userService;

    @Resource
    private PictureService pictureService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 握手之前的检验
     *
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes：给 WebSocketSession 会话设置属性
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            //从请求中获取参数->获取图片id属性参数
            String pictureId = httpServletRequest.getParameter("pictureId");
            //判断需要协作的图片是否存在
            if (StrUtil.isBlank(pictureId)) {
                log.error("缺少图片参数，拒绝握手");
                return false;
            }
            //如果存在这个图片->判断登录用户是否有权限
            User loginUser = userService.getLoginUser(httpServletRequest);
            //判断用户是否登录
            if (ObjUtil.isEmpty(loginUser)) {
                log.error("用户未登录，拒绝握手");
                return false;
            }
            //判断 用户是否有编辑这张图片的权限
            Picture picture = pictureService.getById(pictureId);
            if (ObjUtil.isEmpty(picture)) {
                log.error("图片不存在，拒绝握手");
                return false;
            }
            //获取图片空间id->判断空间是不是存在/判断是不是团队空间
            final Long spaceId = picture.getSpaceId();
            Space space = null;
            if (ObjUtil.isEmpty(spaceId)) {
                log.error("空间ID不存在，拒绝握手");
                return false;
            } else {
                //查询空间
                space = spaceService.getById(spaceId);
                if (ObjUtil.isEmpty(space)) {
                    log.error("图片所在空间不存在，拒绝握手");
                    return false;
                }
                //如果空间存在 但不是团队空间则拒绝握手
                if (SpaceTypeEnum.TEAM.getValue() != space.getSpaceType()) {
                    log.error("图片所在空间不是团队空间，拒绝握手");
                    return false;
                }
                //如果是团队空间则跳出这个if判断
            }
            //获取登录用户的权限列表
            List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
            //判断用户权限列表是否包含图片编辑权限
            if (!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)) {
                log.error("用户没有编辑图片的权限，拒绝握手");
                return false;
            }
            //设置用户登录信息等属性到WebSocket会话中
            attributes.put("user", loginUser);
            attributes.put("userId", loginUser.getId());
            attributes.put("pictureId", Long.valueOf(pictureId)); //转换Long类型 保证获取到的数据精度不丢失
        }
        return true;
    }

    /**
     * 握手之后被调用
     * @param request
     * @param response
     * @param wsHandler
     * @param exception
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
